var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

var Table = require('../utils/commonDBConn').Table;

var crypto  = require('crypto');


passport.serializeUser(function (user, done) {//保存user对象
  done(null, user);//可以通过数据库方式操作
});

passport.deserializeUser(function (user, done) {//删除user对象
  done(null, user);//可以通过数据库方式操作
});

passport.use(new LocalStrategy(
    function (username, password, done) {
      password = crypto.createHash('md5').update(password).digest('hex').toUpperCase();
      var db = new Table();
      var sql;
      if(isNaN(username)){//非数字或者不可转为数字 为数字的话认为是手机号登录
        sql = 'select * from users where username = ? and password = ?';
      }else{
        sql = 'select * from users where phone = ? and password = ?';
      }


        db.executeSql(sql,[username,password],function(err,result){
          if (err||!result||result.length==0) {
            return done(null, false, { message: '用户名或密码错误' });
          }
          return done(null, result[0],{ message: '登录成功' });
        });

    }
));

exports.postlogin = function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {

      req.session.messages =  [info.message];
      //return res.redirect('/login.html');
      return res.send(false);//登录失败
    }
    req.logIn(user, function(err) {
      if (err) { return next(err); }

      if(user.usertype==1){//发车用户
        var data = {
          message:true,
          user:{
            name:user.name,
            nickname:user.nickname
            }
        }
        return res.send(data);
      }
      if(user.usertype==2){//承运用户
        return res.send(false);
      }

    });
  })(req, res, next);
};

exports.logout = function(req, res) {
  req.logout();
  res.redirect('index.html')//退出到登录页
};

// Simple route middleware to ensure user is authenticated.  Otherwise send to login page.
exports.ensureAuthenticated = function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  //res.render('login')
  return res.send(false);
}


// Check for admin middleware, this is unrelated to passport.js
// You can delete this if you use different method to check for admins or don't need admins
exports.ensureAdmin = function ensureAdmin(req, res, next) {
  console.log(req.user);
  if(req.user && req.user.admin === true)
      next();
  else
      res.send(403);
}
